using MediatR;
using TerritoryGame.Application.Commands;
using TerritoryGame.Domain.Entities;
using TerritoryGame.Domain.Repositories;
using TerritoryGame.Domain.ValueObjects;

namespace TerritoryGame.Application.Handlers.CommandHandlers;

public class CreateRoomCommandHandler : IRequestHandler<CreateRoomCommand, CreateRoomResult>
{
    private readonly IGameRoomRepository _roomRepository;
    private readonly IGameRepository _gameRepository;
    
    public CreateRoomCommandHandler(IGameRoomRepository roomRepository, IGameRepository gameRepository)
    {
        _roomRepository = roomRepository;
        _gameRepository = gameRepository;
    }
    
    public async Task<CreateRoomResult> Handle(CreateRoomCommand request, CancellationToken cancellationToken)
    {
        // 添加日志来调试GameDuration
        Console.WriteLine($"CreateRoomCommand received - GameDuration: {request.GameDuration}");
        
        // 创建玩家
        var playerId = Guid.NewGuid();
        var availableColors = PlayerColor.AvailableColors.ToList();
        var playerColor = availableColors[0]; // 第一个玩家使用第一个颜色
        var player = new Player(playerId, request.PlayerNickName, playerColor);
        
        // 创建房间（设置创建者为第一个玩家）
        var roomId = Guid.NewGuid();
        var room = new GameRoom(roomId, request.Name, request.MaxPlayers, request.Password, playerId, request.GameDuration);
        
        // 添加日志来确认房间的GameDuration
        Console.WriteLine($"Room created with GameDuration: {room.GameDuration}");
        
        // 添加玩家到房间
        room.AddPlayer(player);
        
        // 保存房间
        await _roomRepository.AddAsync(room);
        
        // 创建游戏
        var game = new Game(Guid.NewGuid(), room);
        await _gameRepository.AddAsync(game);
        
        return new CreateRoomResult
        {
            Success = true,
            RoomId = roomId,
            PlayerId = playerId,
            PlayerColor = playerColor,
            RoomName = request.Name,
            RoomCode = room.RoomCode // 使用房间实体的房间代码
        };
    }
}
